package dk.dtu.android.gui;

import java.util.ArrayList;
import java.util.Date;

import dk.dtu.android.transport.Constants;
import dk.dtu.android.transport.Helpers;
import dk.dtu.android.transport.R;
import dk.dtu.android.transport.TransportAPI;
import dk.dtu.android.transport.db.KeyValueTable;
import dk.dtu.android.transport.db.PendingRequestTable;
import dk.dtu.android.transport.db.StopstationTable;
import dk.dtu.android.transport.gps.GPSAlarmReceiver;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Debugging extends Activity {
	
	public final static int REQUEST_ID = 28731;
	
	TextView lblDebugText;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.debugging);
		
		Button btnClose = (Button) findViewById(R.id.btnClose);
		Button btnToggleGPS = (Button) findViewById(R.id.btnToggleGPS);
		Button btnClearTable = (Button) findViewById(R.id.btnClearTable);
		lblDebugText = (TextView) findViewById(R.id.lblDebugText);
		Button btnSendUnsent = (Button) findViewById(R.id.btnSendUnsent);
		
		btnClearTable.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				StopstationTable.clearTable();
			}
		});
		btnSendUnsent.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				TransportAPI.sendPendingRequests();
			}
		});
		
		btnClose.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(RESULT_OK, new Intent());
                finish();
			}
		});
		
		btnToggleGPS.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (GPSAlarmReceiver.isAlarmSet(Debugging.this)){
					GPSAlarmReceiver.stopAlarm();
				} 
				else {
					GPSAlarmReceiver.startAlarm();
				}
				GenerateDebugText();
			}
		});
		
		
		GenerateDebugText();
	}
	
	public void GenerateDebugText()
	{
		ArrayList<String> lines = new ArrayList<String>();
		// GPS logger
		lines.add("GPS:");
		if (GPSAlarmReceiver.isAlarmSet(this)){
			lines.add("Alarm is ON.");
		} 
		else {
			lines.add("Alarm is OFF.");
		}
		lines.add("Last log: " + KeyValueTable.getValue(Constants.LAST_GPS_LOG, "Never"));
		Date nextLog = new Date(GPSAlarmReceiver.nextLog());
		lines.add("Next log: " + Helpers.ToXMLDate(nextLog));
		
		// Pending requests
		lines.add("\nPendingRequests:");
		lines.add("Unsent: " + PendingRequestTable.unsentCount());
		
		lblDebugText.setText(TextUtils.join("\n", lines.toArray()));
	}
	
	public static void startThisActivity(Activity activity)
	{
		Intent myIntent = new Intent(activity, Debugging.class);
		activity.startActivityForResult(myIntent, REQUEST_ID);
	}
}
